const fs = require('fs')
const path = require('path')
const { fail } = require('./utils')
const booksPath = path.join(__dirname, 'data/books.json')
function saveBooks(data, res) {
  if (typeof data === 'object') data = JSON.stringify(data)
  return new Promise((resolve, reject) => {
    fs.writeFile(booksPath, data, err => {
      if (err) return fail('服务器内部错误!请联系管理员!', 500, res)
      resolve()
    })
  })
}

function readBooks(res) {
  return new Promise((resolve, reject) => {
    fs.readFile(booksPath, (err, data) => {
      if (err) return fail('服务器内部错误!请联系管理员!', 500, res)
      resolve(JSON.parse(data.toString() || '[]'))
    })
  })
}

module.exports = {
  saveBooks,
  readBooks
}